package com.jingyanzi.privilege.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jingyanzi.privilege.dao.SecurityRoleMapper;
import com.jingyanzi.privilege.dao.SecurityRolebtnMapper;
import com.jingyanzi.privilege.dao.SecurityRolefieldMapper;
import com.jingyanzi.privilege.dao.SecurityRolemenuMapper;
import com.jingyanzi.privilege.dao.SecurityRoletableMapper;
import com.jingyanzi.privilege.domain.BtnDO;
import com.jingyanzi.privilege.domain.DataAccessDO;
import com.jingyanzi.privilege.domain.MenuDO;
import com.jingyanzi.privilege.domain.RoleDO;
import com.jingyanzi.privilege.domain.RoleMenuFromDO;
import com.jingyanzi.privilege.domain.RoleUserDO;
import com.jingyanzi.privilege.domain.result.ResultDO;
import com.jingyanzi.privilege.domain.result.ResultSupport;
import com.jingyanzi.privilege.entity.SecurityRole;
import com.jingyanzi.privilege.entity.SecurityRoleExample;
import com.jingyanzi.privilege.entity.SecurityRoleExample.Criteria;
import com.jingyanzi.privilege.entity.SecurityRolebtn;
import com.jingyanzi.privilege.entity.SecurityRolebtnExample;
import com.jingyanzi.privilege.entity.SecurityRolefieldExample;
import com.jingyanzi.privilege.entity.SecurityRolemenu;
import com.jingyanzi.privilege.entity.SecurityRolemenuExample;
import com.jingyanzi.privilege.entity.SecurityRoletableExample;
import com.jingyanzi.privilege.query.RoleQueryDO;
import com.jingyanzi.privilege.service.IBtnService;
import com.jingyanzi.privilege.service.IDataAccessService;
import com.jingyanzi.privilege.service.IMenuService;
import com.jingyanzi.privilege.service.IRoleService;
import com.jingyanzi.privilege.util.BeanUtilsExtends;

@Service("roleService")
public class RoleServiceImpl extends BaseServiceImpl implements IRoleService {

	@Autowired
	private SecurityRoleMapper roleMapper;

	@Autowired
	private SecurityRolebtnMapper roleBtnMapper;

	@Autowired
	private SecurityRolefieldMapper roleFieldMapper;

	@Autowired
	private SecurityRolemenuMapper roleMenuMapper;

	@Autowired
	private SecurityRoletableMapper roleTableMapper;
	
	@Autowired
	private  IDataAccessService dataAccessService;

	@Autowired
	private IMenuService menuService;

	public ResultDO add(RoleDO roleDO) {

		SecurityRole role = new SecurityRole();

		ResultSupport result = BeanUtilsExtends.copy(role, roleDO);
		if (!result.isSuccess()) {
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("对象转换失败");
			result.setSuccess(false);
			return result;
		}
		// role.setCode(UUID.randomUUID().toString());
		role.setCreatetime(Calendar.getInstance().getTime());
		role.setStatus(1);
		role.setIsDelete(1);
		int r = -1;

		try {
			r = roleMapper.insertSelective(role);
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("添加角色信息失败");
			result.setSuccess(false);
			return result;
		}

		if (r < 1) {
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("添加角色信息失败");
			result.setSuccess(false);
			return result;
		}
		
		
		result.setModel(ResultDO.FIRST_MODEL_KEY, role.getId());
		return result;
	}
	
	public ResultDO checkRepeat(RoleDO domain) {
		
		ResultSupport result = new ResultSupport();
		
		SecurityRoleExample example = new SecurityRoleExample();

		Criteria createCriteria = example.createCriteria();

		createCriteria.andIsDeleteEqualTo(1).andNameCodeEqualTo(domain.getNameCode());
	
		int count = roleMapper.countByExample(example);
		
		result.setModel(ResultSupport.FIRST_MODEL_KEY, count);
		
		return result;
	}

	public ResultDO remove(Integer id) {

		ResultSupport result = new ResultSupport();

		SecurityRole role = new SecurityRole();

		role.setId(id);
		role.setIsDelete(-1);

		int r = -1;

		r = removeMapping(id);

		if (r > -1) {
			try {
				r = -1;
				r = roleMapper.updateByPrimaryKeySelective(role);
			} catch (Exception e) {
				//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
				result.setErrorMsg("删除角色信息失败");
				result.setSuccess(false);
				return result;
			}
		}

		if (r < 1) {
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("删除角色信息失败");
			result.setSuccess(false);
			return result;
		}

		return result;
	}

	public ResultDO modifi(RoleDO roleDO) {

		SecurityRole role = new SecurityRole();

		ResultSupport result = BeanUtilsExtends.copy(role, roleDO);
		if (!result.isSuccess())
			return result;
		role.setCreatetime(Calendar.getInstance().getTime());

		int r = -1;
		try {
			r = roleMapper.updateByPrimaryKeySelective(role);
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("修改角色信息失败");
			result.setSuccess(false);
			return result;
		}
		if (r < 1) {
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("修改角色信息失败");
			result.setSuccess(false);
			return result;
		}

		return result;
	}

	public ResultDO get(Integer id) {

		ResultSupport result = new ResultSupport();

		if (id < 1) {
			result.setErrorCode(ResultDO.ROLE_QUERY_ERROR);
			result.setErrorMsg("获取用户角色出错");
			result.setSuccess(false);
			return result;
		}

		SecurityRole role = null;

		try {
			role = roleMapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("获取角色信息失败");
			result.setSuccess(false);
			return result;
		}

		if (role == null) {
			result.setErrorCode(ResultDO.ROLE_QUERY_ERROR);
			result.setErrorMsg("该角色不存在");
			result.setSuccess(false);
			return result;
		}

		RoleDO roleDO = getRoleDO(role);
		List<MenuDO> menuDOList = getRoleMenu(id);
		//List<BtnDO> btnDOList = getRoleBtn(id);
		roleDO.setMenus(menuDOList);
		//roleDO.setBtnDO(btnDOList);
		result.setModel(ResultSupport.FIRST_MODEL_KEY, roleDO);
		return result;
	}

	private List<MenuDO> getRoleMenu(int roleId) {

		SecurityRolemenuExample example = new SecurityRolemenuExample();
		example.createCriteria().andRoleidEqualTo(roleId);
		List<SecurityRolemenu> list = null;
		try {
			list = roleMenuMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<MenuDO> menuDOList = new ArrayList<MenuDO>();
		for (SecurityRolemenu roleMenu : list) {
			ResultDO resultDO = menuService.get(roleMenu.getMenuid());
			if (!resultDO.isSuccess()) {
				return null;
			}
			menuDOList.add((MenuDO) resultDO.getModel(ResultSupport.FIRST_MODEL_KEY));
		}

		//return menuDOList.stream().sorted(Comparator.comparing(MenuDO::getSortNum)).collect(Collectors.toList());
		return menuDOList;
	}
	
	/*public List<BtnDO> getRoleBtn(int roleId) {

		SecurityRolebtnExample example = new SecurityRolebtnExample();
		example.createCriteria().andRoleidEqualTo(roleId);
		List<SecurityRolebtn> list = null;
		try {
			list = roleBtnMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<BtnDO> btnDOList = new ArrayList<BtnDO>();
		for (SecurityRolebtn roleBtn : list) {
			ResultDO resultDO = btnService.get(roleBtn.getBtnid());
			if (!resultDO.isSuccess()) {
				return null;
			}
			btnDOList.add((BtnDO) resultDO.getModel(ResultSupport.FIRST_MODEL_KEY));
		}

		//return menuDOList.stream().sorted(Comparator.comparing(MenuDO::getSortNum)).collect(Collectors.toList());
		return btnDOList;
	}*/
	
	
	
	
	

	public ResultDO setRoleToMenuAndBtn(RoleMenuFromDO roleMenuFromDO) {

		ResultSupport result = new ResultSupport();

		int roleId = roleMenuFromDO.getRoleId();
		// System.out.println("set roleId:" + roleId);
		SecurityRole role = roleMapper.selectByPrimaryKey(roleId);

		if (role == null) {
			result.setErrorCode(ResultDO.ROLE_QUERY_ERROR);
			result.setErrorMsg("该角色不存在");
			result.setSuccess(false);
			return result;
		}
		
		deleteRoleByMenu(roleId);
		deleteRoleByBtn(roleId);
		
		for(Integer menuId : roleMenuFromDO.getMenus()) {
			// System.out.println("set menuId:" + roleMenuFromDO.getId() + "
			// isCheck:" + roleMenuFromDO.getForIsCheck());
			if (!setRoleMenu(roleId, menuId).isSuccess()) {
				result.setErrorCode(ResultDO.ROLE_QUERY_ERROR);
				result.setErrorMsg("添加角色管理失败");
				result.setSuccess(false);
				return result;
			}
		}
		
		for(Integer btnId : roleMenuFromDO.getBtns()) {

			if (!setRoleBtn(roleId, btnId).isSuccess()) {
				result.setErrorCode(ResultDO.ROLE_QUERY_ERROR);
				result.setErrorMsg("添加角色按钮失败");
				result.setSuccess(false);
				return result;
			}
		}
		
		return result;
	}

	private ResultDO setRoleMenu(int roleId, int menuId) {
		ResultSupport result = new ResultSupport();
		int ret = -1;
	
		SecurityRolemenu roleMenu = new SecurityRolemenu();
		roleMenu.setMenuid(menuId);
		roleMenu.setRoleid(roleId);
		// System.out.println("insert menuId:" + id + " roleId:" +
		// roleId);
		
		try {
			ret = roleMenuMapper.insert(roleMenu);
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("添加角色的菜单失败");
			result.setSuccess(false);
			return result;
		}
		
		if(ret < 0) {
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("添加角色的菜单失败");
			result.setSuccess(false);
			return result;
		}
		
		return result;
	}
	
	private void deleteRoleByMenu(int roleId) {
		SecurityRolemenuExample example = new SecurityRolemenuExample();
		example.createCriteria().andRoleidEqualTo(roleId);
		
		try {
			roleMenuMapper.deleteByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void deleteRoleByBtn(int roleId) {
		SecurityRolebtnExample example = new SecurityRolebtnExample();
		example.createCriteria().andRoleidEqualTo(roleId);
		try {
			roleBtnMapper.deleteByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
/*	
	
	
	private boolean isRoleFormBtn(int roleId, int menuId) {
		SecurityRolemenuExample example = new SecurityRolemenuExample();
		example.createCriteria().andRoleidEqualTo(roleId).andMenuidEqualTo(menuId);
		int count = 0;
		try {
			count = roleMenuMapper.countByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return count == 0 ? true : false;
	}*/
	

	private ResultDO setRoleBtn(int roleId, int btnId) {
		ResultSupport result = new ResultSupport();
		int ret = -1;

		SecurityRolebtn roleBtn = new SecurityRolebtn();
		roleBtn.setBtnid(btnId);
		roleBtn.setRoleid(roleId);
		try {
			ret = roleBtnMapper.insert(roleBtn);
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("添加角色按钮失败");
			result.setSuccess(false);
			return result;
		}

		if (ret < 0) {
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("添加角色按钮失败");
			result.setSuccess(false);
			return result;
		}

		return result;
	}

	public ResultDO list(RoleQueryDO query) {

		ResultSupport result = new ResultSupport();

		List<SecurityRole> list = null;

		SecurityRoleExample example = new SecurityRoleExample();
		Criteria createCriteria = example.createCriteria();
		System.out.println(query.getNameCode());
		if (StringUtils.isNotBlank(query.getNameCode())) {
			createCriteria.andNameCodeLike("%" + query.getNameCode() + "%");
		}
		createCriteria.andIsDeleteEqualTo(1);
		
		example.setOrderByClause("sortNum asc");
		List<RoleDO> roleDOList = null;
		
		try {
			list = roleMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("获取角色信息失败");
			result.setSuccess(false);
			return result;
		}

		roleDOList = getRoleDOList(list);
		result.setModel(ResultSupport.FIRST_MODEL_KEY, roleDOList);

		return result;
	}

	public ResultDO query(RoleQueryDO query) {

		ResultSupport result = new ResultSupport();

		List<SecurityRole> list = null;

		SecurityRoleExample example = new SecurityRoleExample();

		Criteria createCriteria = example.createCriteria();


		createCriteria.andIsDeleteEqualTo(1);

		List<RoleDO> roleDOList = null;

		if (query.isPage()) {
			example.setLimitByPage(query.getStart() + "," + query.getPageRows());
			long count = roleMapper.countByExample(example);
			result.setModel(ResultSupport.SECOND_MODEL_KEY, count);
		}
		
		example.setOrderByClause("sortNum asc");

		try {
			list = roleMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("获取角色信息失败");
			result.setSuccess(false);
			return result;
		}

		roleDOList = getRoleDOList(list);
		result.setModel(ResultSupport.FIRST_MODEL_KEY, roleDOList);

		return result;
	}

	private int removeMapping(int id) {

		SecurityRolebtnExample example1 = new SecurityRolebtnExample();

		example1.createCriteria().andRoleidEqualTo(id);

		int r = -1;

		try {
			r = roleBtnMapper.deleteByExample(example1);
		} catch (Exception e) {
			return -1;
		}

		if (r < -1) {
			return -1;
		}

		r = -1;

		SecurityRolefieldExample example2 = new SecurityRolefieldExample();

		example2.createCriteria().andRoleidEqualTo(id);

		try {
			r = roleFieldMapper.deleteByExample(example2);
		} catch (Exception e) {
			return -1;
		}

		if (r < -1) {
			return -1;
		}

		r = -1;

		SecurityRolemenuExample example3 = new SecurityRolemenuExample();

		example3.createCriteria().andRoleidEqualTo(id);

		try {
			r = roleMenuMapper.deleteByExample(example3);
		} catch (Exception e) {
			return -1;
		}

		if (r < -1) {
			return -1;
		}

		r = -1;

		SecurityRoletableExample example4 = new SecurityRoletableExample();

		example4.createCriteria().andRoleidEqualTo(id);
		try {
			r = roleTableMapper.deleteByExample(example4);
		} catch (Exception e) {
			return -1;
		}

		if (r < -1) {
			return -1;
		}

		r = -1;
		return 1;
	}

	@Override
	public ResultDO cloneRole(RoleDO roleDO) {
		
		SecurityRole role = new SecurityRole();

		ResultSupport result = BeanUtilsExtends.copy(role, roleDO);
		if (!result.isSuccess()) {
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("对象转换失败");
			result.setSuccess(false);
			return result;
		}
		// role.setCode(UUID.randomUUID().toString());
		role.setCreatetime(Calendar.getInstance().getTime());
		role.setStatus(1);
		role.setIsDelete(1);
		int r = -1;

		try {
			r = roleMapper.insert(role);
		} catch (Exception e) {
			e.printStackTrace();
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("添加角色信息失败");
			result.setSuccess(false);
			return result;
		}

		if (r < 1) {
			//result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("添加角色信息失败");
			result.setSuccess(false);
			return result;
		}
		
		
		ResultDO res = get(roleDO.getCloneId());
		
		if(!res.isSuccess()) {
			result.setErrorMsg("获取克隆角色对象失败");
			result.setSuccess(false);
			return result;
		}
		
		RoleDO cloneRole = (RoleDO) res.getModel(ResultDO.FIRST_MODEL_KEY);
		
		for(MenuDO menuDO : cloneRole.getMenus()) {
			SecurityRolemenu roleMenu = new SecurityRolemenu();
			roleMenu.setRoleid(role.getId());
			roleMenu.setMenuid(menuDO.getId());
			try {
				roleMenuMapper.insert(roleMenu);
			} catch(Exception e) {
				e.printStackTrace();
				result.setErrorMsg("设置克隆角色的菜单错误");
				result.setSuccess(false);
				return result;
			}
			
		}
		
		for(BtnDO btnDO : cloneRole.getBtnDO()) {
			SecurityRolebtn roleBtn = new SecurityRolebtn();
			roleBtn.setRoleid(role.getId());
			roleBtn.setBtnid(btnDO.getId());
			try {
				roleBtnMapper.insert(roleBtn);
			} catch(Exception e) {
				e.printStackTrace();
				result.setErrorMsg("设置克隆角色的功能错误");
				result.setSuccess(false);
				return result;
			}
			
		}
	

		result.setModel(ResultDO.FIRST_MODEL_KEY, role.getId());
		return result;
	}
}
